<?php
namespace app\techn_api_n\controller\v1;
use think\Db;
use app\service\PaymentService;
use app\service\TravelService;
use app\service\TechnLastService;
use app\service\OrderService;
class Repair extends Base
{
	public function _initialize()
	{
		parent::_initialize();
	}

	/**
	 * 技师执行补单
	 */
	public function add()
	{
		$this->IsLogin(); //验证登录
		$this->IsTechn(); //验证技师
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        //dump($order_info);
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['techn_is_repair'] != 1 || $order_info['techn_repair_sid'] != 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '无需补单']);
            exit();
        }
        //技师升级
        TechnLastService::TechnLevelUpgradeHandle($order_info['techn_id']);
        //查询是否有机构信息
        // 订单主信息
        $order = [
        	'pid' => $order_info['id'],
        	'order_no' => date('YmdHis').GetRandomStr(6,'int'),
        	'techn_id' => $order_info['techn_id'],
        	'user_id' => $order_info['user_id'],
        	'user_note' => $order_info['user_note'],
        	'payment_id' => 1,
        	'buy_number_duration' => $order_info['buy_number_duration'],
        	'pre_start_time' => $order_info['pre_start_time'],
        	'pre_end_time' => $order_info['pre_end_time'],
        	'travel_id' => $order_info['travel_id'],
        	'distance' => $order_info['distance'],
        	'price' => $order_info['price'],
        	'travel_price' => $order_info['travel_price'],
        	'total_price' => $order_info['price'],
        	//'total_price' => 0.01,
        	'client_type' => ApplicationClientType(),
        	'order_model' => 1,
        	'proxy_id' => $order_info['proxy_id'],
        	'sheng' => $order_info['sheng'],
        	'shi' => $order_info['shi'],
        	'qu' => $order_info['qu'],
        	'add_time' => time(),
        	'upd_time' => time()
        ];
        // 订单添加
        $order_id = Db::name('order')->insertGetId($order);
        if($order_id <= 0)
		{
			echo json_encode(['code' => -1, 'msg' => '订单添加失败']);
            exit();
		}
		$result['code'] = 0;
		$result['msg'] = '下单成功';
		$result['data'] = [
			'order_id' => $order_id
		];
		echo json_encode($result);
	}

	/**
	 * 技师补单订单支付
	 */
	public function pay()
	{
		$this->IsLogin(); //验证登录
		$this->IsTechn(); //验证技师
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['techn'] = $this->techn;
		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'techn_id' => $params['techn']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可支付']);
            exit();
        }
        // 支付方式
        $payment_array = PaymentService::$payment_array;
        $payment = $payment_array[$order_info['payment_id']];
        if(empty($payment))
        {
        	echo json_encode(['code' => -1, 'msg' => '支付方式有误']);
			exit();
        }
        //支付参数
        $pay_data = [
        	'user' => $params['user'],
        	'order_id' => $order_info['id'],
        	'order_no' => $order_info['order_no'],
        	'name' => '技师补单支付',
        	'total_price' => $order_info['total_price'],
        	'client_type' => $order_info['client_type'],
        	'notify_url' => request()->domain().'/techn_api/v1/repair/notify_'.strtolower($payment['payment']),
        	'call_back_url' => '',
        	'redirect_url' => '',
        	'site_name' => '摩小妹',
        	'ajax_url' => '',
        ];
        // 发起支付
        $pay_name = 'payment\\'.$payment['payment'];
        $ret = (new $pay_name($payment['config']['techn']))->Pay($pay_data);
        if(isset($ret['code']) && $ret['code'] == 0)
        {
        	$result = $ret;
        }else
        {
        	$result['code'] = -100;
        	$result['msg'] = empty($ret['msg']) ? '支付接口异常' : $ret['msg'];
        }
        echo json_encode($result);
	}

	/**
	 * 微信支付异步处理技师补单
	 */
	public function notify_weixin()
	{
		//支付方式
		$payment_id = 1;
		$payment_array = PaymentService::$payment_array;
		$payment = $payment_array[$payment_id];
		if(empty($payment))
        {
        	exit();
        }
        $pay_name = 'payment\\'.$payment['payment'];
        $pay_ret = (new $pay_name($payment['config']['techn']))->Respond(array_merge(input('get.'), input('post.')));
        if(!isset($pay_ret['code']) || $pay_ret['code'] != 0)
        {
        	exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['order_no' => $pay_ret['data']['out_trade_no']])->find();
        //订单信息
        if(empty($order_info))
		{
			//资源不存在或已被删除
			exit();
		}
		if($order_info['status'] > 0)
		{
			//状态不可操作
			exit();
		}
		// 支付参数
		$pay_price = isset($pay_ret['data']['pay_price']) ? $pay_ret['data']['pay_price'] : 0;
		// 开启事务
		Db::startTrans();
		//写入支付日志
		$pay_log_id = Db::name('pay_log')->insertGetId([
			'order_id'      => $order_info['id'],
			'trade_no'      => isset($pay_ret['data']['trade_no']) ? $pay_ret['data']['trade_no'] : '',
			'buyer_user'    => isset($pay_ret['data']['buyer_user']) ? $pay_ret['data']['buyer_user'] : '',
			'pay_price'     => $pay_price,
			'total_price'   => $order_info['total_price'],
			'subject'       => isset($pay_ret['data']['subject']) ? $pay_ret['data']['subject'] : '订单支付',
			'payment'       => $payment['payment'],
			'payment_name'  => $payment['name'],
			'business_type' => 1,
			'add_time' => time()
		]);
		if($pay_log_id <= 0)
		{
			Db::rollback();
			//支付日志添加失败
			exit();
		}
		//订单更新数据
		$upd_data = [
			'status' => 6,
			'pay_status' => 1,
			'pay_price' => $pay_price,
			'pay_time' => time(),
			'over_time' => time(),
			'upd_time' => time()
		];
		//更新订单状态
		if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	//订单更新失败
        	exit();
        }
        // 订单状态日志添加
        $status_array = OrderService::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '技师补单完成['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'system',
			'identity_id' => 0,
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			//订单历史状态添加失败
            exit();
		}
		//写入结算数据
		$balance_data = [];
		//结算剩余百分比
		$balance_surplus_scale = 100;
		//服务剩余费用
		$balance_surplus_price = $order_info['price'];
		//查询技师等级写入结算数据
		//查询技师实时数据
		$techn_last_info = Db::name('techn_last')->where(['techn_id' => $order_info['techn_id']])->find();
		if(!empty($techn_last_info))
		{
		    
		    if(!empty($techn_last_info['divide_into'])){
		        
				//如果技师等级存在
				//结算服务分成
				if($balance_surplus_price >= 0.01)
				{
					//技师分成比例
					$techn_divide_into = $techn_last_info['divide_into'];
					//技师分成金额
					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$order_info['price']);
					//技师服务费用结算数据
					$techn_service_data = [
						'balance_type' => 1,
						'order_id' => $order_info['id'],
						'identity_type' => 'techn',
						'identity_id' => $order_info['techn_id'],
						'divide_into' => $techn_divide_into,
						'price' => $order_info['price'],
						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
						'yes_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
						'msg' => '技师分成',
						'status' => 1,
						'add_time' => time(),
						'upd_time' => time()
					];
					$balance_surplus_scale -= $techn_service_data['divide_into'];
					$balance_surplus_price -= $techn_service_data['no_money'];
					$balance_data[] = $techn_service_data;
				}
    				
		    }else{
		        //如果技师实时信息存在查询对应等级
    			//检查等级条件
    			$techn_level_map = [
    				'is_delete_time' => 0,
    				'rank' => $techn_last_info['divide_rank']
    			];
    			$techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
    			if(!empty($techn_level_info))
    			{
    				//如果技师等级存在
    				//结算服务分成
    				if($balance_surplus_price >= 0.01)
    				{
    					//技师分成比例
    					$techn_divide_into = $techn_level_info['divide_into'];
    					//技师分成金额
    					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$order_info['price']);
    					//技师服务费用结算数据
    					$techn_service_data = [
    						'balance_type' => 1,
    						'order_id' => $order_info['id'],
    						'identity_type' => 'techn',
    						'identity_id' => $order_info['techn_id'],
    						'divide_into' => $techn_divide_into,
    						'price' => $order_info['price'],
    						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
    						'yes_money' => $techn_no_money >= 0.01 ? $techn_no_money : $order_info['price'],
    						'msg' => '技师分成',
    						'status' => 1,
    						'add_time' => time(),
    						'upd_time' => time()
    					];
    					$balance_surplus_scale -= $techn_service_data['divide_into'];
    					$balance_surplus_price -= $techn_service_data['no_money'];
    					$balance_data[] = $techn_service_data;
    				}
    			}
		    }
			
		}
		//技师出行费用结算数据
		/*$balance_data[] = [
			'balance_type' => 2,
			'order_id' => $order_info['id'],
			'identity_type' => 'techn',
			'identity_id' => $order_info['techn_id'],
			'divide_into' => 100,
			'price' => $order_info['travel_price'],
			'no_money' => $order_info['travel_price'],
			'yes_money' => $order_info['travel_price'],
			'msg' => '技师出行',
			'status' => 1,
			'add_time' => time(),
			'upd_time' => time()
		];*/
		//查看机构结算数据
		$proxy_info = Db::name('proxy')->where(['proxy_id' => $order_info['proxy_id'], 'commission' => ['GT', 0]])->find();
		if(!empty($proxy_info))
		{
			if($balance_surplus_price >= 0.01)
			{
				//机构分成比例
				$proxy_commission = $proxy_info['commission'];
				//机构分成金额
				$proxy_no_money = PriceNumberFormat(($proxy_commission/100)*$order_info['price']);
				//机构结算数据
				$proxy_service_data = [
					'balance_type' => 1,
					'order_id' => $order_info['id'],
					'identity_type' => 'proxy',
					'identity_id' => $proxy_info['proxy_id'],
					'divide_into' => $proxy_commission,
					'price' => $order_info['price'],
					'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
					'yes_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
					'msg' => '机构分成',
					'status' => 1,
					'add_time' => time(),
					'upd_time' => time()
				];
				$balance_surplus_scale -= $proxy_service_data['divide_into'];
				$balance_surplus_price -= $proxy_service_data['no_money'];
				$balance_data[] = $proxy_service_data;
			}
		}
		//系统平台结算数据
		if($balance_surplus_price >= 0.01)
		{
			$balance_data[] = [
				'balance_type' => 1,
				'order_id' => $order_info['id'],
				'identity_type' => 'system',
				'identity_id' => 0,
				'divide_into' => $balance_surplus_scale,
				'price' => $order_info['price'],
				'no_money' => $balance_surplus_price,
				'yes_money' => $balance_surplus_price,
				'msg' => '平台分成',
				'status' => 1,
				'add_time' => time(),
				'upd_time' => time()
			];
		}
		if(!empty($balance_data))
		{
			$balance_count = Db::name('balance')->insertAll($balance_data);
			if($balance_count != count($balance_data))
			{
				Db::rollback();
				//结算数据添加失败
				exit();
			}
		}
		//处理结算信息
		$balance_list = $balance_data;
		$balance_ph_count = 0;
		foreach($balance_list as $key => $value)
		{
			switch($value['identity_type'])
			{
				//技师
				case 'techn':
				    //获取技师余额
			        $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
			        if(empty($techn_info))
					{
						continue;
					}
					// 更新余额数据
					$techn_money_data = [
						'money' => Db::raw('money+'.$value['no_money']),
			            'upd_time' => time()
					];
					if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
					{
						continue;
					}
					//技师余额日志
					$techn_money_log_id = Db::name('money_log')->insertGetId([
			            'identity_type' => 'techn',
			            'identity_id' => $techn_info['id'],
			            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
			            'money_type' => 0,
			            'operation_type' => 1,
			            'operation_money' => $value['no_money'],
			            'original_money' => $techn_info['money'],
			            'latest_money' => $techn_info['money']+$value['no_money'],
			            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
			            'add_time' => time()
			        ]);
			        if($techn_money_log_id <= 0)
			        {
			        	continue;
			        }
				break;
				//机构
				case 'proxy':
				    //获取机构余额
				    $proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
				    if(empty($proxy_info))
					{
						continue;
					}
					// 更新余额数据
					$proxy_money_data = [
						'money' => Db::raw('money+'.$value['no_money']),
			            'upd_time' => time()
					];
					if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
					{
						continue;
					}
					//机构余额日志
					$proxy_money_log_id = Db::name('money_log')->insertGetId([
			            'identity_type' => 'proxy',
			            'identity_id' => $proxy_info['proxy_id'],
			            'business_type' => 5,
			            'money_type' => 0,
			            'operation_type' => 1,
			            'operation_money' => $value['no_money'],
			            'original_money' => $proxy_info['money'],
			            'latest_money' => $proxy_info['money']+$value['no_money'],
			            'msg' => '机构服务分成费用',
			            'add_time' => time()
			        ]);
			        if($proxy_money_log_id <= 0)
			        {
			        	continue;
			        }
			    break;
			}
			$balance_ph_count++;
		}
		if($balance_ph_count != count($balance_list))
		{
			Db::rollback();
			//结算记录更新失败
			exit();
		}
		//更新父级订单补单状态
		if(!Db::name('order')->where(['id' => $order_info['pid']])->update(['techn_repair_sid' => $order_info['id'], 'upd_time' => time()]))
        {
        	//事务回滚
        	Db::rollback();
        	//订单更新失败
        	exit();
        }
		//提交事务
		Db::commit();
		echo "success";
	}
}